import axios, { AxiosRequestConfig } from 'axios';

// 创建axios实例并配置
const instance = axios.create({
    baseURL: 'http://localhost:3000',
    timeout: 5000,
    headers: { 'X-Custom-Header': 'foobar' }
});

// 定义请求类型
type RequestData = Record<string, any>;
// 封装请求方法
export function request<T>(url: string, method: 'get' | 'post' | 'put' | 'delete', data?: RequestData) {
    const config: AxiosRequestConfig = {
        url,
        method,
        ...(method === 'get' ? { params: data } : { data })
    };
    return instance(config)
        .then(response => response.data as T)
        .catch(error => Promise.reject(error));
}

// 封装GET请求
export function get<T>(url: string, params?: RequestData) {
    return request<T>(url, 'get', params);
}

// 封装POST请求
export function post<T>(url: string, data?: RequestData) {
    return request<T>(url, 'post', data);
}

// 封装PUT请求
export function put<T>(url: string, data?: RequestData) {
    return request<T>(url, 'put', data);
}

// 封装DELETE请求
export function del<T>(url: string, data?: RequestData) {
    return request<T>(url, 'delete', data);
}